package com.project.frba.bifront.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.project.frba.bifront.client.rpc.UserServices;
import com.project.frba.bifront.client.rpc.UserServicesAsync;
import com.project.frba.bifront.client.view.MessageWindow;

public class LoginWindow extends Composite {
	
	private GwtFront parent;
	public  Window mainWindow = new Window();
	private Button	loginButton = new Button("Ingresar");
	private TextField tfUsername;
	private TextField tfPassword;

	
	public LoginWindow(GwtFront parent){
		this.parent = parent;
	
		FormPanel formPanel = new FormPanel();
		formPanel.setPaddings(2);
		formPanel.setLabelWidth(120);
		tfPassword = new TextField("Contraseña", "password", 180);
		tfPassword.setPassword(true);
		tfUsername = new TextField("Nombre de usuario", "username", 180);
		
		formPanel.add(tfUsername);
		formPanel.add(tfPassword);
		
		mainWindow.setTitle("Ingrese a su cuenta");
		mainWindow.setWidth(340);
		mainWindow.add(formPanel);
		mainWindow.setResizable(false);
		loadActions();
		mainWindow.setButtons(new Button[]{loginButton});
		initWidget(mainWindow);
		mainWindow.show();
	}
	
	public void loadActions(){
		loginButton.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				UserServicesAsync userServices = (UserServicesAsync)GWT.create(UserServices.class);
				AsyncCallback<String> loginCallback = new AsyncCallback<String>(){
					public void onSuccess(String sessionId) {
						if(!sessionId.equals("0")){
							tfPassword.setValue("");
							parent.login(sessionId);
							mainWindow.close();
						} else {
							new MessageWindow("Contraseña invalida.");
						}
					}
					
					public void onFailure(Throwable caught) {
						new MessageWindow("Nombre de usuario invalido.");
					}
				};
				userServices.login(tfUsername.getValueAsString(), tfPassword.getValueAsString(), loginCallback);
			}
		});
		
	}
}
